const Result = require('../model/result.model')

const createResult = async ({ userId, questionId, content }) => {
  const result = await Result.create({
    answerer: userId,
    questionId,
    content
  })

  return result
}

const editResultSv = async ({ resultId, content }) => {
  const whereOption = { id: resultId }
  const newResult = {}
  content && Object.assign(newResult, { content })

  return await Result.update(newResult, { where: whereOption })
}

const getResultList = async ({ userId, questionId }) => {
  const whereOption = {}
  userId && Object.assign(whereOption, { id: userId })
  questionId && Object.assign(whereOption, { questionId })

  const result = await Result.findAll({
    where: whereOption,
    order: [['weight', 'DESC'], ['updatedAt']]
  })

  return result
}

const getResultListByUserId = async (userId) => {
  return await getResultList({ userId })
}

const getResultListByQuestionId = async (questionId) => {
  return await getResultList({ questionId })
}

const destroyResultByResultId = async (resultId) => {
  const whereOption = {}
  resultId && Object.assign(whereOption, { id: resultId })

  const result = await Result.destroy({ where: whereOption })

  return result
}

module.exports = {
  createResult,
  editResultSv,
  getResultListByUserId,
  getResultListByQuestionId,
  destroyResultByResultId,
}